package filter.xss;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}

	@Override
	public String getHeader(String name) {
		return StringEscapeUtils.escapeHtml4(super.getHeader(name));
	}

	@Override
	public String getQueryString() {
		return StringEscapeUtils.escapeHtml4(super.getQueryString());
	}

	@Override
	public String getParameter(String name) {
		if (!isJson(super.getParameter(name))) {
			return StringEscapeUtils.escapeHtml4(super.getParameter(name));
		} else {
			return super.getParameter(name);
		}
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values != null) {
			int length = values.length;
			String[] escapseValues = new String[length];
			for (int i = 0; i < length; i++) {
				if (!isJson(values[i])) {
					escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
				} else {
					escapseValues[i] = values[i];
				}
			}
			return escapseValues;
		}
		return super.getParameterValues(name);
	}

	public static boolean isJson(String content) {
		try {
			if (content.contains("[")) {
				JSONObject.parseArray(content);
			} else {
				JSONObject.parseObject(content);
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}